package com.kuhyygy.xml;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import com.kuhyygy.bean.Person;

/**
 * Pull方式解释XML
 * @author KuhYygy
 *
 */
public class PullXmlHandler {
	
	public static List<Person> readXml(InputStream ins) throws Exception {
		List<Person> list = null;
		
		// 先创建XMLPullParser的工厂
		XmlPullParserFactory xpFactory = XmlPullParserFactory.newInstance();
		xpFactory.setNamespaceAware(true);	// 如果有命名空间,必须这样设置
		
		// 获取XML解释器
		XmlPullParser pullPar = xpFactory.newPullParser();
		pullPar.setInput(ins, "UTF-8");
		int eventType = pullPar.getEventType();
		Person p = null;
		while (eventType != XmlPullParser.END_DOCUMENT) {
			switch (eventType) {
			case XmlPullParser.START_DOCUMENT:
				list = new ArrayList<Person>();
				break;
			case XmlPullParser.START_TAG: {
				if ("person".equals(pullPar.getName())) {
					p = new Person();
					p.setId(pullPar.getAttributeValue(0));
				} else if (null != p) {
					if ("name".equals(pullPar.getName())) {
						p.setName(pullPar.nextText());
					} else if ("age".equals(pullPar.getName())) {
						p.setAge(Short.parseShort(pullPar.nextText()));
					}
				}
				break;
			}
			case XmlPullParser.END_TAG: {
				if ("person".equals(pullPar.getName())) {
					if (null != list && null != p) {
						list.add(p);
						p = null;
					}
				}
				break;
			}
			default:
				break;
			}
			eventType = pullPar.next();
		}
		
		return list;
	}

}
